import 'dart:convert';
import 'package:lib_util/SPUtils.dart';
import 'gif/GifSourceBean.dart';
import 'partition/PartitionSourceBean.dart';
import '../../base/SourceType.dart';
import 'graffiti/GraffitiSourceBean.dart';
import 'ColorSourceInterface.dart';
import 'text/TextSourceBean.dart';

class SourceManager {
  //单例
  static SourceManager? _instance;

  static SourceManager get instance => _instance ??= SourceManager._();
  static String SOURCE_KEY = "color_source_key_v1";
  final Map<String, ColorSourceInterface> _sourceMap = {};

  SourceManager._(){
   getSource();
  }

  void saveSource(ColorSourceInterface source) {
    _sourceMap[source.id.toString()] = source;
    String str = jsonEncode(_sourceMap);
    SPUtils.setAsString(SOURCE_KEY, str);
  }

  void deleteSource(ColorSourceInterface source) {
    _sourceMap.remove(source.id.toString());
    String str = jsonEncode(_sourceMap);
    SPUtils.setAsString(SOURCE_KEY, str);
  }

  ColorSourceInterface? getSourceForId(int id) {
    return _sourceMap[id.toString()];
  }

  Map<String, ColorSourceInterface> getSource() {
    if (_sourceMap.isEmpty) {
      String str = SPUtils.getAsString(SOURCE_KEY);
      if (str.isNotEmpty) {
        var map = jsonDecode(str);
        map.forEach((key, value) {
          switch (value["sourceType"]) {
            case SourceType.TYPE_TEXT:
              TextSourceBean bean = TextSourceBean.fromJson(value);
              _sourceMap[key] = bean;
              break;
            case SourceType.TYPE_GRAFFITI:
              GraffitiSourceBean bean = GraffitiSourceBean.fromJson(value);
              _sourceMap[key] = bean;
              break;
            case SourceType.TYPE_GIF:
              GifSourceBean bean = GifSourceBean.fromJson(value);
              _sourceMap[key] = bean;
              break;
            case SourceType.TYPE_PARTITION:
              //分区
              PartitionSourceBean bean = PartitionSourceBean.fromJson(value);
              _sourceMap[key] = bean;
              break;
          }
        });
      }
    }
    return _sourceMap;
  }
}
